<template>
  <div class="wrap">
    <div class="avatar">
      <label>
        <el-avatar :size="90" :src="circleUrl || avatar"></el-avatar>
        <input  id="file" name="file" type="file" ref="file" hidden  @change="onFileChange" />
      </label>
      <b>我的头像</b>
    </div>
      <!-- 修改头像的对话框 -->
    <el-dialog
      title="修改头像"
      :visible.sync="upAvatarDialogVisible"
      width="40%"
      @opened="onvDialogOpened"
      @closed="upAvatarClose"
    >
      <div class="preview-image-wrapper">
        <img :src="previewImage" class="preview-image" ref="preview-image" />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="upAvatarDialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="loading" @click="upAvatarDialogClickOk"
          >{{loading ? '更新中...' : '确 定'}}</el-button
        >
      </span>
    </el-dialog>
    <!-- 修改头像的对话框 结束-->
  </div>
</template>

<script>
import Cropper from "cropperjs";
import "cropperjs/dist/cropper.css";
import { uploadImgMax } from "@/api/upload";
import { editUser } from "@/api/user";
import { mapGetters } from "vuex";
export default {
  name: "Avatar",
  components: {},
  data() {
    return {
       circleUrl: "",
       cropper: null, // 裁切器实例
       loading:false,
        upAvatarDialogVisible: false,
        previewImage: "", //预览图片
    };
  },
  created() {},
  methods: {
     // TODO: 上传到服务器报错 // 点击对话框的确定按钮后 将裁剪的图片上传到服务器
    upAvatarDialogClickOk() {
      // this.circleUrl =this.cropper.getCroppedCanvas().toDataURL('image/png')// bese64图片
      //  const blobData = window.URL.createObjectURL(this.circleUrl);
      //   console.log(blobData);
      this.loading = true;
      this.cropper.getCroppedCanvas().toBlob((file) => {
        let files = new window.File([file], "img.png", { type: "image/png" }); //blob转file，文件名那里不能少了后缀
        // const blobData = window.URL.createObjectURL(file);
        let formData = new FormData();
        formData.append("image", files);
        // 图片上传到服务器
        uploadImgMax(formData)
          .then((result) => {
            this.circleUrl = result.image;
            // 修改头像
            editUser(this.userId, { avatar: this.circleUrl })
              .then((result) => {
                this.$message.success("更新头像成功");
                this.upAvatarDialogVisible = !this.upAvatarDialogVisible;
              })
              .catch((err) => {
                this.$message.error("更新头像失败！");
              });
              this.loading = false;
          })
          .catch((err) => {
            this.$message.error("更新头像失败！，请更换图片重试");
            this.loading = false;
          })
      });
    },
     handleChange() {
      console.log("handleChange");
    },
     onFileChange() {
      const file = this.$refs.file;
      const blobData = window.URL.createObjectURL(file.files[0]);
      this.previewImage = blobData;
      //展示弹出层 用户预览图片
      this.upAvatarDialogVisible = !this.upAvatarDialogVisible;
      // 解决选择相同文件不触发changge事件问题
      this.$refs.file.value = "";
    },
     // 修改头像对话框关闭事件
    upAvatarClose() {
      // 对话框关闭，销毁裁切器
      this.cropper.destroy();
      this.upAvatarDialogVisible = false;
    },
     // Dialog打开动画结束后的回调
    onvDialogOpened() {
      // 因为在对话框中初始化裁切器，所以要等对话框完全打开的状态去初始化
      // 第一次初始化好以后，如果预览裁切器的图片发生了变化，裁切器默认不会更新
      // 如果需要预览图片发生变化更新裁切器：
      // 方式1裁切器的.replace方法
      // if(this.cropper){
      //   this.cropper.replace(this.upAvatarDialogVisibleUrl)
      //   return
      // }
      // 方式2销毁裁切器，重新初始化
      // this.cropper.destroy()
      //获取dom节点
      var image = this.$refs["preview-image"];
      // 初始化裁切器
      this.cropper = new Cropper(image, {
        aspectRatio: 1 / 1, //预览比例
        viewMode: 1, // 不能移除这个画布容器
        dragMode: "none", // 什么都不做 默认crop创建一个画布 ， move移动画布
      });
    },
  },
  computed: {
    ...mapGetters(["nickname", "userId",'avatar']),
  },
};
</script>
<style lang="scss" scoped>
.avatar {
  display:flex;
  align-items: center;
  flex-direction: column;
  margin-left:60px;
  .el-avatar{
    display: block;
    cursor:pointer;
  }
  b{
    margin-top: 10px;
    font-size:14px}
}
.preview-image-wrapper {
  .preview-image {
    display: block;
    max-width: 100%;
    height: 320px;
  }
}
</style>
